package cn.baizhi.controller;


import cn.baizhi.entity.Book;
import cn.baizhi.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LZM
 * @since 2021-11-24
 */
@Controller
@RequestMapping("/books")
@CrossOrigin
public class BookController {

    private static final Logger log = LoggerFactory.getLogger(BookController.class);
    @Autowired
    private BookService bs;

    @GetMapping
    public ResponseEntity<List<Book>> selectAll(){
        List<Book> list = bs.list(null);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }


    @PostMapping
    public ResponseEntity<Void> save(@RequestBody Book book){
        bs.save(book);

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }


    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id){
        log.debug("id: {}",id);
        bs.removeById(id);

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> update(@PathVariable Long id,@RequestBody Book book){
        book.setId(id);
        bs.updateById(book);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Book> selectOne(@PathVariable Long id){
        Book book = bs.getById(id);

        return new ResponseEntity<>(book, HttpStatus.OK);
    }

}

